package com.lifeverse.config;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.actuator.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Prometheus监控配置
 */
@Configuration
@RequiredArgsConstructor
public class PrometheusConfig {

    /**
     * 自定义MeterRegistry配置
     */
    @Bean
    public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
        return registry -> registry.config().commonTags(
                "application", "lifeverse-platform",
                "version", "1.0.0"
        );
    }

    /**
     * 告警相关指标
     */
    @Bean
    public Counter alertCreatedCounter(MeterRegistry meterRegistry) {
        return Counter.builder("lifeverse_alerts_created_total")
                .description("Total number of alerts created")
                .tag("type", "system")
                .register(meterRegistry);
    }

    @Bean
    public Counter alertResolvedCounter(MeterRegistry meterRegistry) {
        return Counter.builder("lifeverse_alerts_resolved_total")
                .description("Total number of alerts resolved")
                .tag("type", "system")
                .register(meterRegistry);
    }

    @Bean
    public Gauge activeAlertsGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_alerts_active")
                .description("Number of active alerts")
                .tag("type", "system")
                .register(meterRegistry, this, PrometheusConfig::getActiveAlertsCount);
    }

    /**
     * 健康检查相关指标
     */
    @Bean
    public Counter healthCheckCounter(MeterRegistry meterRegistry) {
        return Counter.builder("lifeverse_health_checks_total")
                .description("Total number of health checks performed")
                .tag("type", "health")
                .register(meterRegistry);
    }

    @Bean
    public Timer healthCheckTimer(MeterRegistry meterRegistry) {
        return Timer.builder("lifeverse_health_check_duration")
                .description("Health check execution time")
                .tag("type", "health")
                .register(meterRegistry);
    }

    @Bean
    public Gauge healthyServicesGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_services_healthy")
                .description("Number of healthy services")
                .tag("type", "health")
                .register(meterRegistry, this, PrometheusConfig::getHealthyServicesCount);
    }

    @Bean
    public Gauge unhealthyServicesGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_services_unhealthy")
                .description("Number of unhealthy services")
                .tag("type", "health")
                .register(meterRegistry, this, PrometheusConfig::getUnhealthyServicesCount);
    }

    /**
     * 服务发现相关指标
     */
    @Bean
    public Counter serviceRegistrationCounter(MeterRegistry meterRegistry) {
        return Counter.builder("lifeverse_services_registered_total")
                .description("Total number of services registered")
                .tag("type", "discovery")
                .register(meterRegistry);
    }

    @Bean
    public Counter serviceDeregistrationCounter(MeterRegistry meterRegistry) {
        return Counter.builder("lifeverse_services_deregistered_total")
                .description("Total number of services deregistered")
                .tag("type", "discovery")
                .register(meterRegistry);
    }

    @Bean
    public Gauge availableServicesGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_services_available")
                .description("Number of available services")
                .tag("type", "discovery")
                .register(meterRegistry, this, PrometheusConfig::getAvailableServicesCount);
    }

    /**
     * 系统性能相关指标
     */
    @Bean
    public Gauge cpuUsageGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_system_cpu_usage")
                .description("System CPU usage percentage")
                .tag("type", "system")
                .register(meterRegistry, this, PrometheusConfig::getCpuUsage);
    }

    @Bean
    public Gauge memoryUsageGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_system_memory_usage")
                .description("System memory usage percentage")
                .tag("type", "system")
                .register(meterRegistry, this, PrometheusConfig::getMemoryUsage);
    }

    @Bean
    public Gauge diskUsageGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_system_disk_usage")
                .description("System disk usage percentage")
                .tag("type", "system")
                .register(meterRegistry, this, PrometheusConfig::getDiskUsage);
    }

    /**
     * 业务指标
     */
    @Bean
    public Gauge lifeEntitiesGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_life_entities_total")
                .description("Total number of life entities")
                .tag("type", "business")
                .register(meterRegistry, this, PrometheusConfig::getLifeEntitiesCount);
    }

    @Bean
    public Gauge activeLifeEntitiesGauge(MeterRegistry meterRegistry) {
        return Gauge.builder("lifeverse_life_entities_active")
                .description("Number of active life entities")
                .tag("type", "business")
                .register(meterRegistry, this, PrometheusConfig::getActiveLifeEntitiesCount);
    }

    @Bean
    public Counter consciousnessEventsCounter(MeterRegistry meterRegistry) {
        return Counter.builder("lifeverse_consciousness_events_total")
                .description("Total number of consciousness events")
                .tag("type", "business")
                .register(meterRegistry);
    }

    @Bean
    public Counter networkInteractionsCounter(MeterRegistry meterRegistry) {
        return Counter.builder("lifeverse_network_interactions_total")
                .description("Total number of network interactions")
                .tag("type", "business")
                .register(meterRegistry);
    }

    // ==================== 指标获取方法 ====================

    private double getActiveAlertsCount() {
        // 这里应该从AlertService获取实际数据
        return 0.0;
    }

    private double getHealthyServicesCount() {
        // 这里应该从HealthCheckService获取实际数据
        return 0.0;
    }

    private double getUnhealthyServicesCount() {
        // 这里应该从HealthCheckService获取实际数据
        return 0.0;
    }

    private double getAvailableServicesCount() {
        // 这里应该从ServiceDiscoveryService获取实际数据
        return 0.0;
    }

    private double getCpuUsage() {
        // 获取CPU使用率
        return ((com.sun.management.OperatingSystemMXBean) 
                java.lang.management.ManagementFactory.getOperatingSystemMXBean())
                .getProcessCpuLoad() * 100;
    }

    private double getMemoryUsage() {
        // 获取内存使用率
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        return ((double) (totalMemory - freeMemory) / totalMemory) * 100;
    }

    private double getDiskUsage() {
        // 获取磁盘使用率
        java.io.File root = new java.io.File("/");
        long totalSpace = root.getTotalSpace();
        long freeSpace = root.getFreeSpace();
        return ((double) (totalSpace - freeSpace) / totalSpace) * 100;
    }

    private double getLifeEntitiesCount() {
        // 这里应该从LifeEntityService获取实际数据
        return 0.0;
    }

    private double getActiveLifeEntitiesCount() {
        // 这里应该从LifeEntityService获取实际数据
        return 0.0;
    }
}